package cn.swu.cs.lesson11

import android.app.*
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import java.io.File

class MainActivity : AppCompatActivity() {

    val TAG = "@@MAIN"
    private val channelId = "1024"
    private val CODE_CAMERA = 1024
    private val CODE_ALBUM = 1025

    private var channel: NotificationChannel? = null

    private val AUTHORITY = "cn.swu.cs.lesson11.file_provider"

    private var output: Uri? = null

    private var mediaPlayer: MediaPlayer? = null
    private var videoView: VideoView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<Button>(R.id.btn_send_notify).setOnClickListener {
            sendNotify()
        }
        findViewById<Button>(R.id.btn_take_photo).setOnClickListener {
            takePhoto()
        }
        findViewById<Button>(R.id.btn_choose_album).setOnClickListener {
            chooseAlbum()
        }

        initMusic()
        initVideo()
    }

    private fun initMusic() {
        findViewById<Button>(R.id.btn_music_play).setOnClickListener { musicPlay() }
        findViewById<Button>(R.id.btn_music_pause).setOnClickListener { musicPause() }
        findViewById<Button>(R.id.btn_music_resume).setOnClickListener { musicResume() }
        findViewById<Button>(R.id.btn_music_stop).setOnClickListener { musicStop() }

        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer()
        }
        initMedia()
    }

    private var duration = 0
    private var finished = false

    private fun initVideo() {
        findViewById<Button>(R.id.btn_video_play).setOnClickListener { videoPlay() }
        findViewById<Button>(R.id.btn_video_pause).setOnClickListener { videoPause() }
        findViewById<Button>(R.id.btn_video_resume).setOnClickListener { videoResume() }
        findViewById<Button>(R.id.btn_video_stop).setOnClickListener { videoStop() }

        videoView = findViewById<VideoView?>(R.id.video).apply {
            val uri = Uri.parse("android.resource://${BuildConfig.APPLICATION_ID}/${R.raw.video}")
            this.setVideoURI(uri)
            this.setOnPreparedListener {
                this@MainActivity.duration = it.duration
            }
            this.setOnCompletionListener {
                finished = true
            }
            this.setOnInfoListener { mp, what, extra ->
                false
            }
        }
    }

    private fun startToLogProgress() {
        Thread{
            do {
                val current = videoView?.currentPosition ?:0
                Log.d(TAG,"duration - $duration current- $current")
                Thread.sleep(100)
            } while (!finished)
        }.start()
    }

    private fun videoPlay() {
        Log.d(TAG,"start")
        videoView?.start()
        finished = false
        startToLogProgress()
    }

    private fun videoPause() {
        videoView?.pause()
        finished = true
        Log.d(TAG,"pause")
    }

    private fun videoResume() {
        videoView?.start()
        finished = false
        startToLogProgress()
        Log.d(TAG,"resume")
    }


    private fun videoStop() {
        Log.d(TAG,"stop")
        finished = true
        videoView?.pause()
        videoView?.seekTo(0)
    }

    private fun initMedia() {
//        Handler(Looper.getMainLooper()).post {
        val fd = assets.openFd("music.mp3")
        mediaPlayer?.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
        mediaPlayer?.prepare()
//        }
    }

    private fun musicStop() {
        //mediaPlayer?.stop()
        mediaPlayer?.reset()
        initMedia()
    }

    private fun musicResume() {
        mediaPlayer?.start()
    }

    private fun musicPause() {
        mediaPlayer?.pause()
    }

    private fun musicPlay() {
//        initMedia()
        mediaPlayer?.start()
    }

    private fun chooseAlbum() {
        // 1. 创建intent 开启相册
        // 2. 通过 startActivityFroResult
        // 3. 在回调方法中 获取选择结果
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.type = "image/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)

        ActivityCompat.startActivityForResult(this, intent, CODE_ALBUM, null)
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            mediaPlayer?.stop()
            mediaPlayer?.release()

        } catch (e: Exception) {
        }
    }

    private fun takePhoto() {
        // 1. 调用相机应用
        // 2. 传递保存路径
        // 3. 在回调函数 获取结果

        val file = File(externalCacheDir, "output.jpg")
        if (file.exists()) file.delete()
        file.createNewFile()

        output = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(this, AUTHORITY, file)
        } else {
            file.toUri()
//            Uri.fromFile(file)
        }

        val intent = Intent("android.media.action.IMAGE_CAPTURE")
        intent.putExtra(MediaStore.EXTRA_OUTPUT, output)
        ActivityCompat.startActivityForResult(this, intent, CODE_CAMERA, null)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when (requestCode) {
            CODE_CAMERA -> {
                if (resultCode == Activity.RESULT_OK) {
                    renderImgView(output!!)
                }
            }
            CODE_ALBUM -> {
                if (resultCode == Activity.RESULT_OK) {
                    data?.data?.let {
                        renderImgView(it)
                    }
                }
            }
        }

    }

    private fun renderImgView(output: Uri) {
        val fd = contentResolver.openFileDescriptor(output, "r")
        val imgView = findViewById<ImageView>(R.id.img_box)
        imgView.setImageBitmap(
            BitmapFactory.decodeFileDescriptor(fd?.fileDescriptor)
        )
    }

    private fun sendNotify() {
        // 0. 判断支持的最低API版本
        // 1. 创建渠道
        // 2. 创建消息
        // 3. 通过NotificationManager显示消息

        //val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val manager = NotificationManagerCompat.from(this)

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            if (channel == null) {
                channel = NotificationChannel(
                    channelId,
                    "私密",
                    NotificationManager.IMPORTANCE_HIGH
                ).apply {
                    manager.createNotificationChannel(this)
                }
//                channel = NotificationChannelCompat.Builder(
//                    channelId,
//                    NotificationManager.IMPORTANCE_DEFAULT
//                )
//                    .setName("私密")
//                    .build()


            }
        }

        val notify = NotificationCompat.Builder(this, channelId)
            .setContentTitle("西南大学")
            .setContentText("这是一所好学校")
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.me))
            .setSmallIcon(R.drawable.ic_baseline_school_24)
            .setStyle(
                NotificationCompat.BigPictureStyle().bigPicture(
                    BitmapFactory.decodeResource(resources, R.mipmap.swu)
                )
            )
//            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
            .build()

        manager.notify(1, notify)

    }
}